<template>
  <div class="app-container">
    <el-card class="table_style">
      <el-form ref="ruleForm" :model="article" :rules="rules" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="article.title" />
        </el-form-item>
        <el-form-item label="所属品牌">
          <el-select v-model="article.brandId" filterable placeholder="请选择品牌" style="width: 400px">
            <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缩略图" prop="image">
          <el-upload
            class="avatar-uploader"
            :data="qiniuForm"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            action="https://upload.qiniup.com"
          >
            <img v-if="article.image" :src="article.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" prop="author" style="margin-top: 15px;">
          <el-input v-model="article.author" />
        </el-form-item>

        <el-form-item label="文章内容" prop="content">
          <quill-editor ref="QuillEditor" v-model="article.content" :options="editorOption" style="height: 200px;" />
          <!-- 文件上传input 将它隐藏-->
          <el-upload
            ref="upload"
            class="upload-demo"
            action="https://upload.qiniup.com"
            :before-upload="beforeUpload"
            :data="qiniuForm"
            :on-success="uploadContentSuccess"
          >
            <el-button size="small" type="primary" class="uploadImage">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item style="margin-top: 90px;">
          <el-button @click="resetForm('ruleForm')">重置表单</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  ['link', 'image', 'video'],
  ['clean']
]

import { fetchBrandList } from '@/api/brand'
import { fetchArticle, updateArticle } from '@/api/article'
const { v4: uuidv4 } = require('uuid')
import { fetchUpload } from '@/api/upload'
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      editorOption: {
        placeholder: '您想说点什么？',
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                  document.querySelector('.uploadImage').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      article: {
        title: '',
        brandId: '',
        content: '',
        image: '',
        author: '妙手医生'
      },
      brands: [],
      qiniuForm: {
        key: '', // 文件名称
        token: ''
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入文章标题',
            trigger: 'blur'
          }
        ],
        image: [
          {
            required: true,
            message: '请上传缩略图',
            trigger: 'change'
          }
        ],
        content: [
          {
            required: true,
            message: '请填写文章内容',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  async created() {
    const res = await fetchBrandList()
    this.brands = res.data.brands

    // 查出当前要编辑的商品
    const info = await fetchArticle(this.$route.params.id)
    this.article = info.data.article
  },
  methods: {
    // 上传之前
    async beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 如果验证失败，返回假
      if (isJPG && isLt2M === false) return false

      // 如果验证成功，获取token
      const fileType = file.type === 'image/jpeg' ? 'jpg' : 'png' // 获取扩展名
      const res = await fetchUpload()
      this.qiniuForm = {
        key: `${uuidv4()}.${fileType}`, // 文件名称
        token: res.data.uploadToken
      }
      return true
    },

    // 上传成功，获取图片地址
    uploadSuccess(res) {
      this.article.image = 'https://image.holyzq.com/' + res.key
    },
    uploadContentSuccess(res) {
      // 获取富文本组件实例
      const quill = this.$refs.QuillEditor.quill
      // 如果上传成功
      if (res) {
        const imgUrl = 'https://image.holyzq.com/' + res.key
        // 获取光标所在位置
        const length = quill.getSelection().index
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', imgUrl)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const res = await updateArticle(this.$route.params.id, this.article)
        if (res.code === 20000) {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.$router.push({ name: 'Article' })
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleChange(value) {
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dashed #d9d9d9;
}
.upload-demo {
   display: none;
}
</style>
